//
//  ConversionViewController.m
//  AppleMarket
//
//  Created by yangy on 12/11/2018.
//  Copyright © 2018 szgsy. All rights reserved.
//

#import "ConversionViewController.h"
// view
#import "BH_UnderLineTextField.h"
// model
#import "CoinAssetModel.h"
#import "ImageCodeMoel.h"
// controller
#import "SafePwdAlterViewController.h"
#import "InputCodeViewController.h"
#import "ConversionRecordViewController.h"

@interface ConversionViewController ()
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) BH_UnderLineTextField *moneyTF;
@property (nonatomic, strong) BH_UnderLineTextField *countTF;
@property (nonatomic, strong) BH_UnderLineTextField *accountTF;
@property (nonatomic, strong) BH_UnderLineTextField *codeTF;
@property (nonatomic, strong) UIButton *commitButton;
@property (nonatomic, strong) UILabel *explainLabel;
@property (nonatomic, strong) NSString *countStr_;
@property (nonatomic, strong) NSString *accountStr_;
@property (nonatomic, strong) NSString *codeStr_;

@property (nonatomic, assign) NSInteger time;
@property (nonatomic, strong) RACDisposable *disposable;
@end

@implementation ConversionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setNagivationBar];
    [self initViews];
    [self bindViewModel];
}

- (void) setNagivationBar
{
    UIButton *rightButton = [UIButton cm_ButtonWithTitle:@"互转记录" font:kFont(13) titleColor:kColorWithHex(0x4A647A)];
    rightButton.titleLabel.textAlignment = NSTextAlignmentRight;
    rightButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [[rightButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        ConversionRecordViewController *recordVC = [[ConversionRecordViewController alloc] init];
        recordVC.coinModel = self.coinModel;
        [self.navigationController pushViewController:recordVC animated:YES];
    }];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
}

- (void) bindViewModel
{
    RAC(self,countStr_) = _countTF.rac_textSignal;
    RAC(self,accountStr_) = _accountTF.rac_textSignal;
    RAC(self,codeStr_) = _codeTF.rac_textSignal;
    
    RAC(_commitButton,backgroundColor) = [RACSignal combineLatest:@[RACObserve(_countTF, text),RACObserve(_accountTF, text),RACObserve(_codeTF, text)] reduce:^id (NSString *count,NSString *account,NSString *code){
        return (count.length && account.length && code.length)? kColorWithHex(0x3291EB) : kColorWithHex(0xADB7C1);
    }];
    RAC(_commitButton,enabled) = [RACSignal combineLatest:@[RACObserve(_countTF, text),RACObserve(_accountTF, text),RACObserve(_codeTF, text)] reduce:^id (NSString *count,NSString *account,NSString *code){
        return @(count.length && account.length && code.length);
    }];
}

#pragma mark - 发送手机邮箱验证码
- (void) request_SendMsgCode:(NSString*) key code:(NSString*) imageCode
{
    NSString *account = [PlistCommon loginModel].IsMobile? [PlistCommon loginModel].PhoneNumber : [PlistCommon loginModel].Email;
    [SVProgressHUD show];
    [NetRequest request_SendMsgCodeType:@"DoMutualTransfer" account:account code:imageCode key:key completeHandler:^(id  _Nonnull responseObj) {
        if([[responseObj objectForKey:@"Status"] boolValue]){
            [SVProgressHUD showInfoWithStatus:@"发送成功"];
        }else{
            [SVProgressHUD showInfoWithStatus:[responseObj objectForKey:@"Msg"]];
        }
    } fail:^(NSError * _Nonnull error) {
        [SVProgressHUD showInfoWithStatus:@"网络异常"];
    }];
}

#pragma mark - 互转
- (void) request_DoMutualTransfer:(NSString*) safePwd
{
    [SVProgressHUD show];
    [NetRequest request_DoMutualTransferWithVerifyCode:self.codeStr_ ImgCode:nil key:nil account:self.accountStr_ pwd:safePwd amount:self.countStr_ unit:self.coinModel.Unit completeHandler:^(id  _Nonnull responseObj) {
        if([[responseObj objectForKey:@"Status"] boolValue]){
            [SVProgressHUD showInfoWithStatus:@"互转成功"];
        }else{
            [SVProgressHUD showInfoWithStatus:[responseObj objectForKey:@"Msg"]];
        }
    } fail:^(NSError * _Nonnull error) {
        [SVProgressHUD showInfoWithStatus:@"网络异常"];
    }];
}

- (void) initViews
{
    [self.view addSubview:self.titleLabel];
    [self.view addSubview:self.moneyTF];
    [self.view addSubview:self.countTF];
    [self.view addSubview:self.accountTF];
    [self.view addSubview:self.codeTF];
    [self.view addSubview:self.commitButton];
    [self.view addSubview:self.explainLabel];
    [self setViewLayout];
}

- (void) setViewLayout
{
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).offset(30);
        make.top.mas_equalTo(self.view.mas_top).offset(30);
    }];
    
    [_moneyTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.titleLabel);
        make.right.mas_equalTo(self.view.mas_right).offset(-30);
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(47);
    }];
    
    [_countTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.moneyTF.mas_left);
        make.right.mas_equalTo(self.moneyTF.mas_right);
        make.top.mas_equalTo(self.moneyTF.mas_bottom).offset(18);
    }];
    
    [_accountTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.countTF.mas_left);
        make.right.mas_equalTo(self.countTF.mas_right);
        make.top.mas_equalTo(self.countTF.mas_bottom).offset(18);
    }];
    
    [_codeTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.countTF.mas_left);
        make.right.mas_equalTo(self.countTF.mas_right);
        make.top.mas_equalTo(self.accountTF.mas_bottom).offset(18);
    }];
    
    [_commitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.moneyTF);
        make.right.mas_equalTo(self.moneyTF);
        make.top.mas_equalTo(self.codeTF.mas_bottom).offset(45);
        make.height.mas_equalTo(40);
    }];
    
    [_explainLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(-75);
        make.left.mas_equalTo(self.moneyTF);
        make.right.mas_equalTo(self.moneyTF);
    }];
}


- (UILabel *)titleLabel
{
    if(!_titleLabel){
        _titleLabel = [UILabel cm_labelWithText:[NSString stringWithFormat:@"%@互转",self.coinModel.Unit] font:kFontBold(26) textColor:kColorWithHex(0x0E304C)];
    }
    return _titleLabel;
}

- (BH_UnderLineTextField *)moneyTF
{
    if(!_moneyTF){
        _moneyTF = [[BH_UnderLineTextField alloc] initWithFrame:CGRectMake(30, 0, k_ScreenWidth - 60, 44)];
        [_moneyTF setLeftText:@"可转金额" font:kFont(13) color:kColorWithHex(0x4A647A)];
        _moneyTF.rightViewMode = UITextFieldViewModeAlways;
        _moneyTF.rightText = self.coinModel.Unit;
        _moneyTF.rightTextFont = kFontBold(14);
        _moneyTF.rightTextColor = kColorWithHex(0x0E304C);
        _moneyTF.keyboardType = UIKeyboardTypeNumberPad;
        _moneyTF.font = kFontBold(14);
        _moneyTF.enabled = NO;
        _moneyTF.text = [NSString stringWithFormat:@"%lf",self.coinModel.Available];
    }
    return _moneyTF;
}

- (BH_UnderLineTextField *)countTF
{
    if(!_countTF){
        _countTF = [[BH_UnderLineTextField alloc] initWithFrame:CGRectMake(30, 0, k_ScreenWidth - 60, 44)];
        [_countTF setLeftText:@"互转数量" font:kFont(13) color:kColorWithHex(0x4A647A)];
        _countTF.rightViewMode = UITextFieldViewModeAlways;
        _countTF.rightText = self.coinModel.Unit;
        _countTF.rightTextFont = kFontBold(14);
        _countTF.rightTextColor = kColorWithHex(0x0E304C);
        _countTF.keyboardType = UIKeyboardTypeNumberPad;
        _countTF.font = kFontBold(14);
    }
    return _countTF;
}

- (BH_UnderLineTextField *)accountTF
{
    if(!_accountTF){
        _accountTF = [[BH_UnderLineTextField alloc] initWithFrame:CGRectMake(30, 0, k_ScreenWidth - 60, 44)];
        [_accountTF setLeftText:@"对方账户" font:kFont(13) color:kColorWithHex(0x4A647A)];
        _accountTF.keyboardType = UIKeyboardTypeNumberPad;
        _accountTF.font = kFontBold(14);
    }
    return _accountTF;
}

- (BH_UnderLineTextField *)codeTF
{
    if(!_codeTF){
        _codeTF = [[BH_UnderLineTextField alloc] init];
        _codeTF.placeholder = @"请输入验证码";
        _codeTF.font = kFont(13);
        _codeTF.rightViewMode = UITextFieldViewModeAlways;
        _codeTF.rightText = @"获取验证码";
        _codeTF.rightTextFont = kFont(13);
        _codeTF.rightTextColor = kColorWithHex(0x3291EB);
        @weakify(self);
        _codeTF.rightHanlder = ^{
            // 点击获取验证码
            @strongify(self);
            UIButton *sendButton = (UIButton*)self.codeTF.rightView;
            sendButton.enabled = NO;
            self.time = 60;
            self.disposable = [[RACSignal interval:1.0 onScheduler:[RACScheduler mainThreadScheduler]] subscribeNext:^(NSDate * _Nullable x) {
                self.time -- ;
                NSString *title = self.time > 0 ? [NSString stringWithFormat:@"%lds",self.time] : @"重新发送";
                UIColor *bgColor =  self.time > 0 ? kColorWithHex(0xADB7C1) : kColorWithHex(0x3291EB);
                [sendButton setTitle:title forState:UIControlStateNormal | UIControlStateDisabled];
                [sendButton setTitleColor:bgColor forState:UIControlStateNormal | UIControlStateDisabled];
                sendButton.enabled = (self.time <= 0) ? YES : NO;
                if(self.time == 0){
                    [self.disposable dispose];
                }
            }];
            InputCodeViewController *codeVC = [InputCodeViewController inputCodeViewControllerWithCodeType:CodeTypeDoMutualTransfer];
            codeVC.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.85];
            codeVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            codeVC.completeHandler = ^(ImageCodeMoel * _Nonnull codeModel,NSString *inputCodeStr) {
                [self request_SendMsgCode:codeModel.ImgKey code:inputCodeStr];
            };
            [self presentViewController:codeVC animated:YES completion:nil];
        };
    }
    return _codeTF;
}

- (UIButton *)commitButton
{
    if(!_commitButton){
        _commitButton = [UIButton cm_ButtonWithTitle:@"提交" font:kFontBold(14) titleColor:[UIColor whiteColor] bgColor:kColorWithHex(0xADB7C1)];
        _commitButton.layer.cornerRadius = 2;
        [[_commitButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            NSString *message = [NSString stringWithFormat:@"对方姓名 %@\n对方账号 %@\n币种 %@\n数量 %@\n",@"",self.accountStr_,self.coinModel.Unit,self.countStr_];
            UIAlertController *alterVC = [UIAlertController alertControllerWithTitle:@"互转确认" message:message preferredStyle:UIAlertControllerStyleAlert];
            [alterVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
            [alterVC addAction:[UIAlertAction actionWithTitle:@"确认互转" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                SafePwdAlterViewController *pwdVC = [[SafePwdAlterViewController alloc] init];
                pwdVC.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.85];
                pwdVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
                pwdVC.completeHandler = ^(NSString * _Nonnull pwdStr_) {
                    // 请求互转接口
                    [self request_DoMutualTransfer:pwdStr_];
                };
                [self presentViewController:pwdVC animated:YES completion:nil];
            }]];
            [self presentViewController:alterVC animated:YES completion:nil];
        }];
    }
    return _commitButton;
}

- (UILabel *)explainLabel
{
    if(!_explainLabel){
        _explainLabel = [UILabel cm_labelWithText:@"" font:kFontBold(12) textColor:kColorWithHex(0xADB7C1)];
    }
    return _explainLabel;
}

@end
